﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Camelot.JSONAPI.Business
{
    public static class CommandType
    {
        /// <summary>
        /// Detect the command type from a SQL Query
        /// </summary>
        /// <param name="sharePointQuery"></param>
        /// <returns></returns>
        public static Models.CommandType? QueryType(this string sharePointQuery)
        {
            var m = sharePointQuery.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (m.Length <= 0)
                return null;

            var command = m[0].ToUpper();

            // Allowed commands
            var commands = new List<string> { "SHOW", "SELECT", "INSERT", "UPDATE", "DELETE", "CALL", "USE" };
            if (commands.Exists(x => x.Equals(command)))
            {
                // Make a queryable out of the enum values
                IQueryable<Models.CommandType> commandTypes = Enum.GetValues(typeof(Models.CommandType)).AsQueryable().Cast<Models.CommandType>();

                // Convert the inserted string to a CommandType
                Models.CommandType commandToCompare = (Models.CommandType)Enum.Parse(typeof(Models.CommandType), commands.Single(x => x.Equals(command)));

                // return the outcome, possibly null if no match
                return commandTypes.Single(x => x.Equals(commandToCompare));
            }

            return null;
        }

    }
}
